package com.js.myapp.system.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.js.basicpage.activity.BaseLoadingDialogActivity;
import com.js.basicutils.NetUtils;
import com.js.basicutils.PreferenceNetWorkUtil;
import com.js.basicutils.StringUtils;
import com.js.basicutils.ToastUtils;
import com.js.myapp.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


// Created by JS on 2020/7/13.

public class NetworkSettingActivity extends BaseLoadingDialogActivity {

    private static final int CONNECT_PORT_IP = 1;
    @BindView(R.id.header_back)
    LinearLayout headerBack;
    @BindView(R.id.centre_title)
    TextView centreTitle;
    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.header)
    RelativeLayout header;
    @BindView(R.id.et_ip)
    EditText etIp;
    @BindView(R.id.iv_ip)
    ImageView ivIp;
    @BindView(R.id.et_port)
    EditText etPort;
    @BindView(R.id.iv_port)
    ImageView ivPort;
    @BindView(R.id.btn_restore)
    Button btnRestore;
    @BindView(R.id.btn_test)
    Button btnTest;

    public static void start(Context context) {
        Intent intent = new Intent(context, NetworkSettingActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int originFlag = getWindow().getDecorView().getSystemUiVisibility();
        getWindow().getDecorView().setSystemUiVisibility(originFlag | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_network_setting);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        centreTitle.setText("网络设置");
        rightTitle.setText("确定");
        String serverIP = PreferenceNetWorkUtil.getServerIP(this);
        String serverPort = PreferenceNetWorkUtil.getServerPort(this);
        etIp.setText(serverIP);
        etPort.setText(serverPort);
    }

    @OnClick({R.id.header_back, R.id.right_title, R.id.iv_ip, R.id.iv_port, R.id.btn_restore, R.id.btn_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.header_back:
                finish();
                break;
            case R.id.right_title:
                saveIpPort();
                break;
            case R.id.iv_ip:
                etIp.setText("");
                break;
            case R.id.iv_port:
                etPort.setText("");
                break;
            case R.id.btn_restore:
                restore();
                break;
            case R.id.btn_test:
                test();
                break;
        }
    }

    /**
     * 保存IP和端口
     */
    private void saveIpPort() {
        String ip = etIp.getText().toString().trim();
        String port = etPort.getText().toString().trim();
        if (isIpPortInvalid(ip, port)) return;
        PreferenceNetWorkUtil.saveNetInfo(this, ip, port);
        ToastUtils.showToast(this, "保存成功！");
        finish();
    }

    /**
     * 恢复设置
     */
    private void restore() {
        String serverIP = PreferenceNetWorkUtil.getServerIP(this);
        String serverPort = PreferenceNetWorkUtil.getServerPort(this);
        etIp.setText("218.76.24.159");
        etPort.setText("9014");
    }

    /**
     *  网络测试
     */
    private void test() {
        if (!NetUtils.isConnected(this)) {
            ToastUtils.showToast(this, "网络未连接~");
            return;
        }
        String ip = etIp.getText().toString().trim();
        String port = etPort.getText().toString().trim();
//        LogUtils.d(this, ip + ", " + port);
        if (isIpPortInvalid(ip, port)) return;
        showDialog(this, "网络监测中...");
        new Thread(() -> {
            boolean isConnect = NetUtils.isHostConnectable(ip, Integer.parseInt(port));
            Message msg = new Message();
            msg.what = CONNECT_PORT_IP;
            msg.obj = isConnect;
            mHandler.sendMessage(msg);
        }).start();

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            dismissDialog();
            switch (msg.what) {
                case CONNECT_PORT_IP:
                    boolean isConnect = (Boolean) msg.obj;
                    if (isConnect) {
                        ToastUtils.showToast(NetworkSettingActivity.this, "IP,端口可连接！");
                    } else {
                        ToastUtils.showToast(NetworkSettingActivity.this, "IP,端口不可连接！");
                    }
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 检查ip和端口是否合法
     * @param ip ip
     * @param port 端口
     * @return boolean
     */
    private boolean isIpPortInvalid(String ip, String port) {
        if (TextUtils.isEmpty(ip)) {
            ToastUtils.showToast(this, "请输入服务器IP地址！");
            return true;
        }
        if(!StringUtils.isIp(ip)) {
            Toast.makeText(this, "IP格式不正确！", Toast.LENGTH_SHORT).show();
            return true;
        }
        if (TextUtils.isEmpty(port)) {
            ToastUtils.showToast(this, "请输入服务器端口！");
            return true;
        }
        return false;
    }
}
